<template>
    <div class="asideInfo">
        <div class="box">
            <div class="top_nav">
                <div class="">
                    <span>选择日期:</span>
                    <div class="date-content">
                        <input type="text" id="start_time" class="start_time" readonly v-model="selectTime.beginTime">
                        <label for="start_time"></label>
                        <date-pick v-if="DPStatus.BEGINDatePickStatus" @node-click="getDate"></date-pick>
                        <div class="img_box">
                            <img src="../../assets/images/reports_image/mileage_selected-.png" class="dateIcon noHide"
                                 alt="选择日期"
                                 @click="updateDPStatus('BEGINDatePickStatus')">
                        </div>
                    </div>
                    <div class="date-content">
                        <input type="text" class="end_time" id="end_time" readonly v-model="selectTime.endTime">
                        <label for="end_time"></label>
                        <div class="img_box">
                            <img src="../../assets/images/reports_image/mileage_selected-.png" class="dateIcon noHide"
                                 alt="选择日期"
                                 @click="updateDPStatus('ENDDatePickStatus')">
                        </div>
                        <date-pick v-if="DPStatus.ENDDatePickStatus" @node-click="getDate"></date-pick>
                    </div>
                    <span class="shortcut_date">
                         <span @click="getTodayTime()">今天</span>&nbsp;|&nbsp;
                         <span @click="getYesterdayTime()">昨天</span>&nbsp;|&nbsp;
                         <span @click="getThreeDays()">近三天</span>&nbsp;|&nbsp;
                         <span @click="getSevenDays()">近七天</span>
                    </span>
                </div>
                <div class="equipChoose dropdown" :class="{open: isOpen}">
                    <label for="equipChoose">设备或组:</label>
                    <input type="text" id="equipChoose" placeholder="请选择设备或组" data-toggle="dropdown" readonly
                           aria-haspopup="true"
                           :aria-expanded="isOpen" @click="dropDown" v-model="equipChoose">
                    <div class="dropdown-menu" aria-labelledby="equipChoose">
                        <equip-group @getGroup="groupHide" @getEquip="getEquip"></equip-group>
                    </div>
                    <div class="btnGroup">
                        <button type="button" class="btn btn-success search" @click="search">搜索</button>
                        <button type="button" class="btn btn-success export" @click="exportExcel">导出</button>
                    </div>
                </div>
            </div>
            <div class="table">
                <table>
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>设备号(IMEI)</th>
                        <th>设备名称</th>
                        <th>车牌号</th>
                        <th>所属客户</th>
                        <th>开始时间</th>
                        <th>结束时间</th>
                        <th>持续时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(equip, index) in alarmDetail">
                        <td>{{ index + 1 }}</td>
                        <td>{{ equip.imei }}</td>
                        <td>{{ equip.equipName }}</td>
                        <td>{{ equip.carNumber }}</td>
                        <td>{{ equip.userNickname }}</td>
                        <td>{{ equip.createTime }}</td>
                        <td>{{ equip.updateTime }}</td>
                        <td>{{ equip.durationTime }}</td>
                        <td><span class="detail" @click="toDetail(equip)">明细</span></td>
                    </tr>
                    </tbody>
                </table>
                <div class="text-center customer-table-color">
                    <pagination :total="total" :current-page='current' @pageChange="pageChange"></pagination>
                </div>
            </div>
        </div>
        <!--底部页面显示数据条数-->
        <div class="myButtonMenu">
            <div>
                <span>
                  每页显示条数
                  <label>
                      <select name="pageSize" v-model="pageSize" @change="pageSizeChange">
                          <option value="10">10</option>
                          <option value="20">20</option>
                          <option value="30">30</option>
                          <option value="40">40</option>
                          <option value="50">50</option>
                          <option value="100">100</option>
                      </select>
                  </label>
                  条
                </span>
            </div>
        </div>
        <driving-detail ref="trafficDetail"></driving-detail>
    </div>
</template>
<script>
    import equipGroup from '@/components/equipOrGroup/equipOrGroup'
    import pagination from '@/components/pagination/pagination'
    import DatePick from '@/base/DatePick' //引入日期选择器组件
    import drivingDetail from '@/components/drivingDetail/drivingDetail'

    export default {
        data () {
            return {
                isOpen: false,  //是否显示设备或组选择框
                equipChoose: '', //设备或组的值
                total: 0, // 记录总条数
                display: 10, // 每页显示条数
                current: 1, // 当前的页数
                DPStatus: {
                    BEGINDatePickStatus: false, //开始日期选择器的状态
                    ENDDatePickStatus: false //结束日期选择器的状态
                },
                selectTime: {
                    beginTime: '',
                    endTime: ''
                },
                alarmDetail: {}, // 报警记录表格数据
                pageSize: 10,
                dealerId: undefined,
                equipName: undefined,
                isSearch: false, // 保存是否搜索
            }
        },
        methods: {
            groupHide (data) {
                this.isOpen = false
                this.equipChoose = data.value
                this.dealerId = data.id
                this.equipName = undefined
            },
            getEquip (data) {
                this.equipChoose = data.equipName
                this.dealerId = undefined
                this.equipName = data.equipName
            },
            dropDown () {
                this.isOpen = true
            },
            // 分页组件
            pageChange (currentPage) {
                if (this.isSearch) {
                    this.search()
                } else {
                    this.getTableData(currentPage, this.display)
                }
            },
            pageSizeChange () {
                this.display = this.pageSize * 1
                this.current = 1
                this.pageChange(1)
            },
            // 隐藏时间选择器
            hideDatePicker (e) {
                if (!$(e.target).hasClass('noHide') && !$(e.target).parents().hasClass('noHide')) {
                    for (let key in this.DPStatus) {
                        if (this.DPStatus.hasOwnProperty(key)) {
                            this.DPStatus[key] = false
                        }
                    }
                }
            },
            updateDPStatus (params) {
                for (let key in this.DPStatus) {
                    if (this.DPStatus.hasOwnProperty(key)) {
                        this.DPStatus[key] = false
                    }
                }
                this.DPStatus[params] = true
            },
            getDate (date) {
                if (date === '') {
                    for (let key in this.DPStatus) {
                        if (this.DPStatus.hasOwnProperty(key)) {
                            this.DPStatus[key] = false
                        }
                    }
                    return
                }
                if (this.DPStatus.BEGINDatePickStatus) {
                    this.selectTime.beginTime = date
                } else {
                    this.selectTime.endTime = date
                }
                for (let key in this.DPStatus) {
                    if (this.DPStatus.hasOwnProperty(key)) {
                        this.DPStatus[key] = false
                    }
                }
            },
            dataFormat (time, fmt) {
                let thisTime = new Date(time)
                let o = {
                    'M+': thisTime.getMonth() + 1, //月份
                    'd+': thisTime.getDate(), //日
                    'h+': thisTime.getHours(), //小时
                    'm+': thisTime.getMinutes(), //分
                    's+': thisTime.getSeconds(), //秒
                    'q+': Math.floor((thisTime.getMonth() + 3) / 3), //季度
                    'S': thisTime.getMilliseconds() //毫秒
                }
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
                for (let k in o)
                    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                return fmt
            },
            setEndTime () {
                let a = new Date()
                const hour = a.getHours() < 10 ? '0' + a.getHours() : a.getHours()
                const min = a.getMinutes() < 10 ? '0' + a.getMinutes() : a.getMinutes()
                const miao = a.getSeconds() < 10 ? '0' + a.getSeconds() : a.getSeconds()
                this.selectTime.endTime = this.dataFormat(a, `yyyy-MM-dd ${hour}:${min}:${miao}`)
            },
            getTodayTime () {
                let a = new Date()
                this.selectTime.beginTime = this.dataFormat(a, 'yyyy-MM-dd 00:00:00')
                this.setEndTime()
            },
            getYesterdayTime () {
                let timestamp = Date.parse(new Date())
                let a = new Date(timestamp - 60 * 60 * 24 * 1000)
                this.selectTime.beginTime = this.dataFormat(a, 'yyyy-MM-dd 00:00:00')
                this.setEndTime()
            },
            getThreeDays () {
                let timestamp = Date.parse(new Date())
                let a = new Date(timestamp - 60 * 60 * 24 * 3 * 1000)
                this.selectTime.beginTime = this.dataFormat(a, 'yyyy-MM-dd 00:00:00')
                this.setEndTime()
            },
            getSevenDays () {
                let timestamp = Date.parse(new Date())
                let a = new Date(timestamp - 60 * 60 * 24 * 7 * 1000)
                this.selectTime.beginTime = this.dataFormat(a, 'yyyy-MM-dd 00:00:00')
                this.setEndTime()
            },
            // 页面初始化得到当前时间
            initGetDate () {
                let today = new Date()
                let year = today.getFullYear()
                let month = today.getMonth() + 1
                if (month < 10) {
                    month = `0${month}`
                }
                let date = today.getDate() < 10 ? '0' + today.getDate() : today.getDate()
                let hour = today.getHours() < 10 ? '0' + today.getHours() : today.getHours()
                let min = today.getMinutes() < 10 ? '0' + today.getMinutes() : today.getMinutes()
                let miao = today.getSeconds() < 10 ? '0' + today.getSeconds() : today.getSeconds()
                this.selectTime.beginTime = `${year}-${month}-${date} ${hour}:${min}:${miao}`
                this.selectTime.endTime = `${year}-${month}-${date} ${hour}:${min}:${miao}`
            },
            // 表格数据
            getTableData (pageNum, pageSize) {
                let params = {
                    pageNum: pageNum,
                    pageSize: pageSize
                }
                this.$ajax
                    .report
                    .alarmRecord(params)
                    .then(res => {
                        let data = res.data
                        if (data.code === 200) {
                            this.alarmDetail = data.result.content
                            this.total = data.result.numberOfElements
                        } else if (data.code === 408) {
                            this.$store.commit('showAlert', {error: this.$msgDictionary.loginGetaway})
                            let timer = setTimeout(() => {
                                clearTimeout(timer)
                                $('#msgModal').modal('hide')
                                this.$router.push({path: '/login'})
                            }, 2000)
                        } else {
                            this.$store.commit('showAlert', {error: data.msg})
                        }
                    }, () => {
                        this.$store.commit('showAlert', {error: this.$msgDictionary.serviceException})
                    })
            },
            // 搜索按钮
            search () {
                if (this.equipChoose === '') {
                    this.$store.commit('showAlert', {error: this.$msgDictionary.emptyEquipOrGroup})
                    return
                }
                let params = {
                    pageNum: 1,
                    pageSize: this.display,
                    beginDate: this.selectTime.beginTime,
                    endDate: this.selectTime.endTime,
                }
                if (this.dealerId) {
                    params.dealerId = this.dealerId
                } else if (this.equipName) {
                    params.equipName = this.equipName
                }
                this.$ajax
                    .report
                    .queryRecord(params)
                    .then(res => {
                        let data = res.data
                        if (data.code === 200) {
                            if (data.result.content === undefined || data.result.content.length === 0) {
                                this.$store.commit('showAlert', {error: this.$msgDictionary.queryEmpty})
                                this.equipChoose = ''
                                this.dealerId = undefined
                                this.equipName = undefined
                                this.alarmDetail = {}
                                return
                            }
                            this.isSearch = true
                            this.alarmDetail = data.result.content
                            this.total = data.result.numberOfElements
                        } else if (data.code === 408) {
                            this.$store.commit('showAlert', {error: this.$msgDictionary.loginGetaway})
                            let timer = setTimeout(() => {
                                clearTimeout(timer)
                                $('#msgModal').modal('hide')
                                this.$router.push({path: '/login'})
                            }, 2000)
                        } else {
                            this.$store.commit('showAlert', {error: data.msg})
                        }
                    }, () => {
                        this.$store.commit('showAlert', {error: this.$msgDictionary.serviceException})
                    })
            },
            exportExcel () {
                if (this.equipChoose === '') {
                    this.$store.commit('showAlert', {error: this.$msgDictionary.emptyEquipOrGroup})
                    return
                }
                let params = {
                    pageNum: 1,
                    pageSize: this.display,
                    beginDate: this.selectTime.beginTime,
                    endDate: this.selectTime.endTime,
                }
                let a = document.createElement('a')
                a.setAttribute('target', '_blank')
                if (this.dealerId) {
                    params.dealerId = this.dealerId
                    a.setAttribute('href', 'https://car.so360.org/obd/excel/alarmPrompt/otherConditions?dealerId=' + this.dealerId
                        + '&beginDate=' + this.selectTime.beginTime + '&endDate=' + this.selectTime.endTime
                    )
                } else if (this.equipName) {
                    params.equipName = this.equipName
                    a.setAttribute('href', 'https://car.so360.org/obd/excel/alarmPrompt/otherConditions?equipName=' + this.equipName
                        + '&beginDate=' + this.selectTime.beginTime + '&endDate=' + this.selectTime.endTime
                    )
                }
                this.$ajax
                    .report
                    .excelDriving(params)
                    .then(res => {
                        let data = res.data
                        if (data.code === 401) {
                            this.$store.commit('showAlert', {error: data.msg})
                        } else {
                            a.click()
                        }
                        a = null
                    }, () => {
                        this.$store.commit('showAlert', {error: this.$msgDictionary.serviceException})
                        a = null
                    })
            },
            /**
             * 行车明细
             */
            toDetail (data) {
                this.$ajax
                    .report
                    .queryByIdType(data.userId, data.type)
                    .then(res => {
                        let data = res.data
                        if (data.code === 200) {
                            $(' #drivingDetail').modal('toggle')
                            if (data.result === undefined || data.result === null) {
                                return
                            }
                            this.$refs.trafficDetail.getData(data.result.content)
                        } else if (data.code === 408) {
                            this.$store.commit('showAlert', {error: this.$msgDictionary.loginGetaway})
                            let timer = setTimeout(() => {
                                clearTimeout(timer)
                                $('#msgModal').modal('hide')
                                this.$router.push({path: '/login'})
                            }, 2000)
                        } else {
                            this.$store.commit('showAlert', {error: data.msg})
                        }
                    }, () => {
                        this.$store.commit('showAlert', {error: this.$msgDictionary.serviceException})
                    })
            }
        },
        mounted () {
            this.initGetDate()
            this.getTableData(1, this.display)
            this.$globalClick(this.hideDatePicker)
        },
        components: {
            equipGroup,
            pagination,
            DatePick,
            drivingDetail
        }
    }
</script>
<style scoped>
    * {
        padding: 0;
    }

    input, select {
        background: transparent;
        border: 1px solid #ccc;
        outline: none;
        border-radius: 4px;
        height: 30px;
    }

    .top_nav .equipChoose {
        margin-top: 0.28rem;
    }

    .top_nav label {
        font-weight: normal;
        color: #333;
    }

    .top_nav .equipChoose input {
        width: 2rem;
        padding-left: 10px;
        padding-right: 0.3rem;
        background: url("../../assets/images/reports_image/mileage_selected-.png") no-repeat 1.85rem;
    }

    .dropdown-menu {
        left: 53px;
        top: 27px;
        width: 5.4rem;
        padding: 10px;
    }

    .dateIcon {
        width: 16px;
        height: 14px;
        cursor: pointer;
    }

    .asideInfo {
        flex: 1;
    }

    /* 底部显示条数样式 */
    .myButtonMenu {
        position: fixed;
        bottom: 0.5rem;
        margin-left: 0.2rem;
    }

    /* 右侧主体 头部 标题样式 */

    .table .detail {
        cursor: pointer;
    }

    .date-content {
        position: relative;
        display: inline-block;
        border: 0;
        margin-right: 0.2rem;
    }

    .shortcut_date span {
        cursor: pointer;
    }

    .shortcut_date span:hover {
        color: #17D29C;
    }

    /* ---------- */
    .box {
        clear: both;
        background: white;
    }

    .top_nav {
        position: relative;
        height: 1.48rem;
        padding-top: 0.2rem;
        padding-left: 0.2rem;
        padding-bottom: 0.29rem;
        background: rgb(233, 246, 242);
        box-shadow: 0 5px 5px #DCE9E5 inset;
    }

    .img_box {
        display: inline;
        position: absolute;
        right: 12px;
        top: 0.07rem;
    }

    .img_box img {
        width: 15px;
        height: 15px;
    }

    .start_time,
    .end_time {
        width: 2.1rem;
        height: 30px;
        border-radius: 4px;
        padding-left: 10px;
        font-size: 0.12rem;
    }

    #equipChoose {
        width: 2.1rem;
    }

    .btnGroup {
        margin-left: 1rem;
        display: inline-block;
    }

    .btnGroup [type='radio'] {
        height: auto;
        width: auto;
        margin-bottom: -10px;
    }

    .btnGroup button {
        width: 1.2rem;
        height: 0.4rem;
        padding-top: 0;
        line-height: 0.4rem;
        color: rgb(23, 203, 156);
        background-color: transparent;
        border-radius: 4px;
        border: 1px solid #ccc;
        outline: none;
    }

    .btnGroup button:hover {
        background-color: #e6e6e6;
    }

    .btnGroup .search {
        background: #17D29C;
        color: #fff;
    }

    .btnGroup .search:hover {
        background-color: #25CB73;
    }
</style>
